package com.wstuo.itsm.web;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;

import ognl.DefaultTypeConverter;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.wstuo.common.config.basicConfig.service.ITimeZoneService;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.util.TimeUtils;

/**
 * 时区转换类
 * @author Ciel
 *
 */
public class DateConverter extends DefaultTypeConverter{
	 private static final Logger LOGGER = Logger.getLogger(DateConverter.class);
     @Autowired
 	 private ITimeZoneService timeZoneService;
     @Autowired
     private AppContext appctx;
     /**
      * Convert value between types
      */
     @SuppressWarnings("rawtypes")
	public Object convertValue(Map ognlContext, Object value, Class toType) {
             Object result = null;
             if (toType == Date.class) {
                     try {
						result = doConvertToDate(value);
						//客户端时区转成服务端时区
						result = clientToServerTimeZone(result);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						LOGGER.error("Converting from milliseconds to Date fails!");
					}
             } else if (toType == String.class) {
                     result = doConvertToString(value);
             }
             return result;
     }

     /**
      * Convert String to Date
      *
      * @param value
      * @return Date
     * @throws ParseException 
      */
     private Date doConvertToDate(Object value) throws ParseException{
    	 
             Date result = null;

             if (value instanceof String) {
             
                     result = DateUtils.parseDate((String) value, new String[] { TimeUtils.DATE_PATTERN, TimeUtils.DATETIME_PATTERN, TimeUtils.MONTH_PATTERN ,TimeUtils.DATETIME_HOURS,TimeUtils.DATETIME_MILLISECOND});
                     // all patterns failed, try a milliseconds constructor
                     if (result == null && StringUtils.isNotEmpty((String)value)) {

                             try {
                                     result = new Date(new Long((String) value).longValue());
                             } catch (Exception e) {
                                     LOGGER.error("Converting from milliseconds to Date fails!");
                             }

                     }

             } else if (value instanceof Object[]) {
                     // let's try to convert the first element only
                     Object[] array = (Object[]) value;

                     if ((array != null) && (array.length >= 1)) {
                             value = array[0];
                             result = doConvertToDate(value);
                     }

             } else if (Date.class.isAssignableFrom(value.getClass())) {
                     result = (Date) value;
             }
  
             return result;
     }

     /**
      * 获取客户端时区转化为系统时区
      * @param date
      * @return Date
      */
     private Date clientToServerTimeZone(Object date){
    	 TimeZone ctz = TimeZone.getDefault(); 
    	 try {
        	 //得到客户端时区
        	 String clientTimeZone = appctx.getAttributeByName("clientTimeZone");
        	 ctz = TimeZone.getTimeZone(clientTimeZone);
		} catch (Exception e) {
			// TODO: handle exception
			ctz = timeZoneService.getDefaultTimeZone("enduserTimeZone");
		}
    	 
    	 Date d = (Date)date;
    	 
		//将当前时间转为标准时间
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(d.getTime()-ctz.getOffset(d.getTime()));
		
		//得到标准时间
		Date dete1 = cal.getTime();
		
		
		Calendar cal1 = Calendar.getInstance();
		
		cal1.setTimeInMillis(dete1.getTime()+TimeZone.getDefault().getRawOffset());
    	 
    	 return cal1.getTime();
		
     }
     
     /**
      * Convert Date to String
      *
      * @param value
      * @return
      */
     private String doConvertToString(Object value) {
             SimpleDateFormat simpleDateFormat = new SimpleDateFormat(TimeUtils.DATETIME_PATTERN);
             String result = null;
             if (value instanceof Date) {
                     result = simpleDateFormat.format(value);
             }
             return result;
     }
     
}
